package timing.ukulele.third.msgChannel.action.send;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import timing.ukulele.third.dictionary.msg.MsgChannelType;
import timing.ukulele.third.msgChannel.model.SendTaskInfo;
import timing.ukulele.third.service.common.SysThirdPartyUserService;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 * 后置参数检查以及处理
 * @author zh
 */
@Slf4j
@Service
public class SendAfterCheckAndProcessAction {

    @Autowired
    private SysThirdPartyUserService sysThirdPartyUserService;

    public static final String PHONE_REGEX_EXP = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[0-9])|(18[0-9])|(19[1,8,9]))\\d{8}$";
    public static final String EMAIL_REGEX_EXP = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";

    /**
     * 邮件和手机号正则
     */
    protected static final Map<Integer, String> CHANNEL_REGEX_EXP;

    static {
        Map<Integer, String> tempMap = new HashMap<>();
        tempMap.put(MsgChannelType.ALYSms.getCode(), PHONE_REGEX_EXP);
        tempMap.put(MsgChannelType.EMAIL.getCode(), EMAIL_REGEX_EXP);
        // 初始化为不可变集合，避免被恶意修改
        CHANNEL_REGEX_EXP = Collections.unmodifiableMap(tempMap);
    }

    public void process(SendTaskInfo sendTaskInfo) {
        // 获取发送渠道
        Integer sendChannel = sendTaskInfo.getSendChannel();
        // 根据渠道获取对应接受者信息

        // 过滤不合理接受者
        filter(sendTaskInfo, CHANNEL_REGEX_EXP.get(sendChannel));
    }

    /**
     * 利用正则过滤掉不合法的接收者
     * @param sendTaskInfo
     * @param regexExp
     */
    private void filter(SendTaskInfo sendTaskInfo, String regexExp) {
        Set<String> illegalPhone = sendTaskInfo.getReceiver().stream()
                .filter(phone -> !ReUtil.isMatch(regexExp, phone))
                .collect(Collectors.toSet());
        if (CollUtil.isNotEmpty(illegalPhone)) {
            sendTaskInfo.getReceiver().removeAll(illegalPhone);
            log.error("messageTemplateId:{} find illegal receiver!{}",
                    sendTaskInfo.getMessageTemplateId(), JSON.toJSONString(illegalPhone));
        }
    }

}
